/*******************************************************************************
 * Copyright (c) 2010 Sylvain Sicard.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Sylvain Sicard - initial API and implementation
 ******************************************************************************/
package com.googlecode.ssdutils.beanconverter.factory;

import org.springframework.beans.factory.FactoryBean;

import com.googlecode.ssdutils.beanconverter.api.BeanConverter;
import com.googlecode.ssdutils.beanconverter.api.BeanConverterFactory;


/**
 * @author Sylvain Sicard
 * @param <S>
 * @param <T>
 * 
 */
public class BeanConverterFactoryBeanImpl<S, T> implements
		FactoryBean<BeanConverter<S, T>> {

	private BeanConverterFactory<S, T> converterFactory;

	private Class<S> sourceClass;

	private Class<T> targetClass;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.beans.factory.FactoryBean#getObject()
	 */
	public BeanConverter<S, T> getObject() throws Exception {
		return converterFactory.getConverter(sourceClass, targetClass);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.beans.factory.FactoryBean#getObjectType()
	 */
	@SuppressWarnings("rawtypes")
	public Class<BeanConverter> getObjectType() {
		return BeanConverter.class;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.beans.factory.FactoryBean#isSingleton()
	 */
	public boolean isSingleton() {
		return true;
	}

	public void setConverterFactory(BeanConverterFactory<S, T> converterFactory) {
		this.converterFactory = converterFactory;
	}

	@SuppressWarnings("unchecked")
	public void setSourceClass(String sourceClass)
			throws ClassNotFoundException {
		this.sourceClass = (Class<S>) getClass(sourceClass);
	}

	@SuppressWarnings("unchecked")
	public void setTargetClass(String targetClass)
			throws ClassNotFoundException {
		this.targetClass = (Class<T>) getClass(targetClass);
	}

	/**
	 * @param targetClass2
	 * @return
	 * @throws ClassNotFoundException
	 */
	private Class<?> getClass(String className) throws ClassNotFoundException {
		ClassLoader cl = this.getClass().getClassLoader();
		return cl.loadClass(className);
	}

}
